/*
 * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.sugar.note;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
//import android.content.DialogInterface;
//import android.content.DialogInterface.OnClickListener;
//import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.media.AudioManager;
import android.media.AudioManager.OnAudioFocusChangeListener;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.provider.Settings;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;

//import net.micode.notes.R;
//import net.micode.notes.data.Notes;
//import net.micode.notes.tool.DataUtils;


import java.io.IOException;
import java.lang.reflect.Method;

import android.util.Log;
import android.content.ContentUris;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.content.BroadcastReceiver;
import android.content.IntentFilter;

public class AlarmAlertActivity extends Activity{  //implements OnClickListener, OnDismissListener
    private long mNoteId;
    private static final String TAG = "AlarmAlertActivity";
    private String mSnippet = "";
    private static final int SNIPPET_PREW_MAX_LEN = 60;
    MediaPlayer mPlayer;
    private Button mButtonOK;
    private Button mButtonEnter;
    private Context mCtx;
    private TextView mAlarmText;
    private static final int EVENT_NOTE_ALARMALERT = 3000;
    private static final int NOTE_ALARMALERT_TIME = 300000;//300000
    private static final int NOTE_ALARMALERT_INTERVAL_TIME = 300000;
    private NoteHomeReceiver mReceiverHome = new NoteHomeReceiver();
    private IntentFilter mIntentFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
    //private ArrayList<NoteItem> notelist;
    
    //fukang.li date20151024 for MYOSL-464,start
    private boolean mAudioFocus = false;
    AudioManager mAudioManager;
    OnAudioFocusChangeListener afChangeListener;
    //fukang.li date20151024 for MYOSL-464,end
    static final int NOTIFICATION_ID = 0x1123;
    private boolean isAudioStop = false;
    int alert_num;
    private static final int FLAG_HOMEKEY_DISPATCHED = 0x80000000;

    private Handler mAlarmAlertHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            
            switch (msg.what) {
            case EVENT_NOTE_ALARMALERT:
           /*
		int alert_num = PublicUtils.getAlarmAlertNum(mCtx.getContentResolver(), mNoteId);
		if (alert_num >= 1)
		{
	              long AlarmAlertTime = 0;
		      long Currtime = System.currentTimeMillis();
		      AlarmAlertTime = Currtime + NOTE_ALARMALERT_INTERVAL_TIME;
                      Intent intent = new Intent(mCtx, AlarmReceiver.class);
	              Uri noteUri = ContentUris.withAppendedId(NotePad.Notes.CONTENT_ID_URI_BASE, mNoteId);
                      intent.setData(noteUri);   //mWorkingNote.getNoteId()
                      PendingIntent pendingIntent = PendingIntent.getBroadcast(mCtx, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
                      AlarmManager alarmManager = ((AlarmManager) getSystemService(ALARM_SERVICE));
                      alarmManager.set(AlarmManager.RTC_WAKEUP, AlarmAlertTime, pendingIntent);
		      
		      stopAlarmSound();
                      finish();
		}
		else
		{
                      closeNoteAlarmDialog();
		}
	  */
                    isAudioStop = true;
                    abandonAudioFocus();//
                    stopAlarmSound();
                    final Window win = getWindow();
                    win.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.note_alarm_dialog);
        mCtx = this;
        mIntentFilter.addAction(PublicUtils.ACTION_ALERT_CLOSE);
        mIntentFilter.addAction(PublicUtils.ACTION_ALERT_VIEW);
        mIntentFilter.addAction(PublicUtils.ACTION_NOTEALARM_DELETE);
        registerReceiver(mReceiverHome, mIntentFilter);

        final Window win = getWindow();
        win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);

        win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
                | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
//                | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON// fukang.li
                | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR
                | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);

        
        
        alert_num = PublicUtils.getAlarmAlertNum(mCtx.getContentResolver(), mNoteId);
        // notelist = intent.getParcelableArrayListExtra("notelist");

        mButtonOK = (Button) findViewById(R.id.id_button_ok);
        mButtonEnter = (Button) findViewById(R.id.id_button_enter);

        mButtonOK.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // Uri noteUri = ContentUris.withAppendedId(NotePad.Notes.CONTENT_ID_URI_BASE,
                // mNoteId);
                closeNoteAlarmDialog();
                // PublicUtils.updateNoteAlertNum(mCtx.getContentResolver(), 0, noteUri);
            }
        });
       
       mButtonEnter.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
			      closeNoteAlarmDialog();
			      Intent intent = new Intent(mCtx, NoteView.class);
	              Uri noteUri = ContentUris.withAppendedId(NotePad.Notes.CONTENT_ID_URI_BASE, mNoteId);
			      //PublicUtils.updateNoteAlertNum(mCtx.getContentResolver(), 0, noteUri);
                  intent.setData(noteUri);
				  intent.putExtra("AlarmStartNoteView", true);
				  startActivity(intent);
			}
		});

        mAlarmText = (TextView)findViewById(R.id.note_alarm_dialog_text);

        try {
            Log.e(TAG, "noteId:" + mNoteId);
            mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1));
            mSnippet = PublicUtils.getSnippetById(this.getContentResolver(), mNoteId);
            mSnippet = mSnippet.length() > SNIPPET_PREW_MAX_LEN ? mSnippet.substring(0,
                    SNIPPET_PREW_MAX_LEN) + getResources().getString(R.string.notelist_string_info)
                    : mSnippet;

            if (savedInstanceState != null) {// fukang.li date20151105
                Log.e(TAG, "savedInstanceState != null");
                long alarmDate = PublicUtils.getAlarmDateByUri(getContentResolver(),
                        intent.getData());
                 long timeStay = System.currentTimeMillis() - alarmDate;
                if (timeStay > 3000){
                    finish();
                    return;
                }
            }
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            return;
        }

        if (!mSnippet.equals("")) {
            mAlarmText.setText(mSnippet);
        } else {
            mAlarmText.setText(R.string.default_note_text);
        }
        
        
        //
        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        
        afChangeListener = new OnAudioFocusChangeListener() {
            public void onAudioFocusChange(int focusChange) {
                switch (focusChange) {
                    case AudioManager.AUDIOFOCUS_GAIN:
                        Log.i(TAG, "AudioFocusChange AUDIOFOCUS_GAIN");
                        mAudioFocus = true;
//                        if(mPlayer == null && !isAudioStop)
//                            initMediaPlayer();
//                        else if(!mPlayer.isPlaying() && !isAudioStop)
//                            mPlayer.start();
                        if (mPlayer != null && !mPlayer.isPlaying() && !isAudioStop) {
                            mPlayer.start();
                        }
                        if(mPlayer != null){
                            mPlayer.setVolume(1.0f, 1.0f);
                        }
                        break;
                    case AudioManager.AUDIOFOCUS_GAIN_TRANSIENT:
                        Log.i(TAG, "AudioFocusChange AUDIOFOCUS_GAIN_TRANSIENT");
                        mAudioFocus = true;
//                        if(mPlayer == null && !isAudioStop)
//                            initMediaPlayer();
//                        else if(!mPlayer.isPlaying() && !isAudioStop)
//                            mPlayer.start();
                        if (mPlayer != null && !mPlayer.isPlaying() && !isAudioStop) {
                            mPlayer.start();
                        }
                        if (mPlayer != null)
                            mPlayer.setVolume(1.0f, 1.0f);
                        break;
                    case AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK:
                        Log.i(TAG, "AudioFocusChange AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK");
                        mAudioFocus = true;
                        break;
                    case AudioManager.AUDIOFOCUS_LOSS:
                        Log.i(TAG, "AudioFocusChange AUDIOFOCUS_LOSS");
                        mAudioFocus = false;
//                        stopAlarmSound();
                        break;
                    case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
                        Log.i(TAG, "AudioFocusChange AUDIOFOCUS_LOSS_TRANSIENT");
                        mAudioFocus = false;
                        if(mPlayer != null && mPlayer.isPlaying())
                            mPlayer.pause();
//                        stopAlarmSound();
                        break;
                    case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
                        Log.i(TAG, "AudioFocusChange AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK");
                        mAudioFocus = false;
                        if(mPlayer != null && mPlayer.isPlaying())
//                            mPlayer.setVolume(0.1f, 0.1f);
                        break;
                    default:
                        Log.i(TAG, "AudioFocusChange focus = " + focusChange);
                        break;
                }
            }
        };
        
        //Log.i("AlarmAlert","before new ");
        //mPlayer = new MediaPlayer();
//        Log.i("AlarmAlert","after new before play");
        if (PublicUtils.visibleInNoteDatabase(getContentResolver(), mNoteId)) {
//            showActionDialog();
            showNotice();
            requestAudioFocus();
//            Boolean isAlarmReceive = getIntent().getExtras().getBoolean("isAlarmReceive", false);
            if(mAudioFocus && !isAudioStop)
                initMediaPlayer();
            Log.i(TAG, "over onCreate");
        } else {
            Log.e(TAG,"not exist");
            finish();
        }
        
        // Uri noteUri = ContentUris.withAppendedId(NotePad.Notes.CONTENT_ID_URI_BASE, mNoteId);
        // int alert_num = PublicUtils.getAlarmAlertNum(mCtx.getContentResolver(), mNoteId);
        // PublicUtils.updateNoteAlertNum(getContentResolver(), alert_num - 1, noteUri);
        mAlarmAlertHandler.sendEmptyMessageDelayed(EVENT_NOTE_ALARMALERT, NOTE_ALARMALERT_TIME);
    }

    public void showNotice(){
        Intent mIntent = new Intent(this,this.getClass());
        mIntent.setData(getIntent().getData());
        PendingIntent pi = PendingIntent.getActivity(this, (int)mNoteId, mIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        Intent enterIntent = new Intent(this, NoteView.class);
        Uri noteUri = ContentUris.withAppendedId(NotePad.Notes.CONTENT_ID_URI_BASE, mNoteId);
        enterIntent.setData(noteUri);
        enterIntent.putExtra("AlarmStartNoteView", true);
        enterIntent.putExtra("notifyId", (int) (NOTIFICATION_ID + mNoteId));
        PendingIntent enterPendingIntent = PendingIntent.getActivity(this, 0, enterIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        
//        Intent enterIntent = new Intent(PublicUtils.ACTION_ALERT_VIEW);
//        Uri noteUri = ContentUris.withAppendedId(NotePad.Notes.CONTENT_ID_URI_BASE, mNoteId);
//        enterIntent.putExtra("URI", noteUri);
//        PendingIntent enterPendingIntent = PendingIntent.getBroadcast(this, (int)mNoteId, enterIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        
        //START
        Notification.Builder builder = new Notification.Builder(this);
        builder.setSmallIcon(R.drawable.stat_notify_alarm)
        .setTicker(mAlarmText.getText())
        .setWhen(0)
        .setContentTitle(getResources().getString(R.string.note_alarm_title))
        .setContentText(mAlarmText.getText())
        .setContentIntent(enterPendingIntent)
        .setAutoCancel(false)
        .setDefaults(Notification.DEFAULT_LIGHTS)
        //.setDeleteIntent(createClearMissedCallsIntent())
        .setPriority(Notification.PRIORITY_HIGH)
//        .setNumber(alert_num)
//        .setFullScreenIntent(enterPendingIntent, true)
        .setOngoing(true);
        
//        Notification notification = builder.getNotification();
        // notification.flags = Notification.FLAG_NO_CLEAR;
        // if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
        builder.addAction(R.drawable.stat_notify_chat,
                getString(R.string.notealert_enter),
                enterPendingIntent);

        Intent closeIntent = new Intent(PublicUtils.ACTION_ALERT_CLOSE);
        closeIntent.putExtra("URI", noteUri);
        closeIntent.putExtra("notifyId", (int) (NOTIFICATION_ID + mNoteId));
        PendingIntent closePendingIntent = PendingIntent.getBroadcast(mCtx, (int) mNoteId, closeIntent, 0);
        builder.addAction(R.drawable.ic_cancel,
                getString(R.string.notealert_ok),
                closePendingIntent);

        // END

//        Notification notify = new Notification();
//        notify.icon = R.drawable.app_notes;
//        if (!mSnippet.equals("")) {
//            notify.tickerText = mSnippet;
//        } else {
//            notify.tickerText = getResources().getString(R.string.default_note_text);
//        }
//        notify.when = System.currentTimeMillis();
//        notify.defaults = Notification.DEFAULT_LIGHTS;
//        notify.flags = Notification.FLAG_NO_CLEAR;
//        notify.setLatestEventInfo(mCtx, getResources().getString(R.string.note_alarm_title), notify.tickerText, pi);
        
        
        NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        //send
        notificationManager.notify((int) (NOTIFICATION_ID + mNoteId), builder.build());
    }
    
    public void closeNotice(){
        NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        notificationManager.cancel((int) (NOTIFICATION_ID + mNoteId));
    }
    
    public void closeNoteAlarmDialog() {
	
        Log.e("nb alarm", "AlarmAlertActivity andy3344  closeNoteAlarmDialog");
        Intent intent = new Intent(PublicUtils.ACTION_NOTEALARM_ALERT);
        sendBroadcast(intent);
        abandonAudioFocus();//
        stopAlarmSound();
        closeNotice();
        finish();
    }

    private boolean isScreenOn() {
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        return pm.isScreenOn();
    }

    private void playAlarmSound() {
        Log.i("AlarmAlert","playAlarmSound AA");
        
        // fukang.li date20151014 for MYOSL-464
        // sendMusicAction(CMDPAUSE);
        
        
        Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM);

        int silentModeStreams = Settings.System.getInt(getContentResolver(),
                Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0);

        Log.i("AlarmAlert","url:"+url.toString());
        Log.i("AlarmAlert","silentModeStreams:"+ silentModeStreams);
        
        if ((silentModeStreams & (1 << AudioManager.STREAM_ALARM)) != 0) {
            mPlayer.setAudioStreamType(silentModeStreams);
        } else {
            mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
        }
        try {
            mPlayer.reset();mPlayer.setDataSource(this, url);
            mPlayer.setLooping(true);
            mPlayer.prepare();
            mPlayer.start();
            Log.i("AlarmAlert","playAlarmSound mPlayer.start()");
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void stopAlarmSound() {
        if (mPlayer != null) {
            mPlayer.stop();
            mPlayer.reset();//
            mPlayer.release();
            mPlayer = null;
            //sendMusicAction(CMDPLAY);
        }
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //fukang.li date20151016 for MYOSL-431
        switch (keyCode)
        {
        case KeyEvent.KEYCODE_BACK:
            Log.e(TAG,"BACK");
//            closeNoteAlarmDialog();
            return true;
        case KeyEvent.KEYCODE_HOME:
//            closeNoteAlarmDialog();
            Log.e(TAG,"HOME");
            return true;
        default:
            break;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        Log.i(TAG,"onDestroy()");
        unregisterReceiver(mReceiverHome);
        abandonAudioFocus();
        stopAlarmSound();//
        closeNotice();
        super.onDestroy();
    }
    
    @Override
    protected void onPause() {
        super.onPause();
    }
    
    @Override
    protected void onResume() {
        Log.d(TAG,"onResume()");
        super.onResume();
    }
    
    @Override
    protected void onStop() {
        Log.d(TAG,"onStop()");
        super.onStop();
    }
    
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        Log.i(TAG,"onSaveInstanceState");
        super.onSaveInstanceState(outState);
    }

    private class NoteHomeReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
                String reason = intent.getStringExtra("reason");
                if (reason != null && reason.equals("homekey")) {
                    // home
                    // stopAlarmSound();
                }
                else if ("recentapps".equals(reason)) {
                    
                }
            } else if (action.equals(PublicUtils.ACTION_ALERT_CLOSE)) {// fukang.li date20151023
                Uri noteUri = ContentUris
                        .withAppendedId(NotePad.Notes.CONTENT_ID_URI_BASE, mNoteId);
                Uri muri = (Uri) intent.getExtras().get("URI");
                if (noteUri != null && noteUri.equals(muri)) {
                    closeNoteAlarmDialog();
                }
            } else if (action.equals(PublicUtils.ACTION_NOTEALARM_DELETE)) {
                Uri noteUri = ContentUris
                        .withAppendedId(NotePad.Notes.CONTENT_ID_URI_BASE, mNoteId);
                Uri muri = (Uri) intent.getExtras().get("URI");
                if (noteUri != null && noteUri.equals(muri)) {
                    abandonAudioFocus();
                    stopAlarmSound();
                }
            } else if (action.equals(PublicUtils.ACTION_ALERT_VIEW)) {
                Uri noteUri = ContentUris
                        .withAppendedId(NotePad.Notes.CONTENT_ID_URI_BASE, mNoteId);
                Uri muri = (Uri) intent.getExtras().get("URI");
                if (noteUri != null && noteUri.equals(muri)) {
                    Intent enterIntent = new Intent(mCtx, NoteView.class);
                    enterIntent.setData(noteUri);
                    enterIntent.putExtra("AlarmStartNoteView", true);
                    closeNoteAlarmDialog();
                    startActivity(enterIntent);
                }
                collapseStatusBar(mCtx);//
            }

        }
    }
    
    /**
     * fukang.li
     * date20151024 for MYOSL-464
     */
    private void requestAudioFocus() {
        Log.v(TAG, "requestAudioFocus mAudioFocus = " + mAudioFocus);
        if (!mAudioFocus) {
            int result = mAudioManager.requestAudioFocus(afChangeListener,
                    AudioManager.STREAM_MUSIC, // Use the music stream.
                    AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
            if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
                mAudioFocus = true;
            } else {
                Log.e(TAG, "AudioManager request Audio Focus result = " + result);
            }
        }
    }

    private void abandonAudioFocus() {
        Log.v(TAG, "abandonAudioFocus mAudioFocus = " + mAudioFocus);
        if (mAudioFocus) {
            mAudioManager.abandonAudioFocus(afChangeListener);
            mAudioFocus = false;
        }
    }
    
    private void initMediaPlayer(){
        if(isAudioStop)
            return;
        Log.i("AlarmAlert","before new ");
        mPlayer = new MediaPlayer();
        Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM);
//        mPlayer = MediaPlayer.create(this, url);
        Log.i("AlarmAlert","after new before play");
        

        int silentModeStreams = Settings.System.getInt(getContentResolver(),
                Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0);

        Log.i("AlarmAlert","url:"+url.toString());
        Log.i("AlarmAlert","silentModeStreams:"+ silentModeStreams);
        
        if ((silentModeStreams & (1 << AudioManager.STREAM_ALARM)) != 0) {
            mPlayer.setAudioStreamType(silentModeStreams);
        } else {
            mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
        }
        try {
            //mPlayer.reset();
            mPlayer.setDataSource(this, url);
            mPlayer.setLooping(true);
            mPlayer.prepare();
//            mPlayer.
            mPlayer.start();
            Log.i("AlarmAlert","playAlarmSound mPlayer.start()");
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } 
        catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void collapseStatusBar(Context context) {
        try {
            Object statusBarManager = context.getSystemService("statusbar");
            Method collapse;
            if (Build.VERSION.SDK_INT <= 16) {
                collapse = statusBarManager.getClass().getMethod("collapse");
            } else {
                collapse = statusBarManager.getClass().getMethod("collapsePanels");
            }
            collapse.invoke(statusBarManager);
        } catch (Exception localException) {
            localException.printStackTrace();
        }
    }


}
